﻿using System.Data.Entity;


namespace FlexPlatform.Common
{
    using FlexPlatform.Shared.Configuration;
    using FlexPlatform.Shared.DataModel;
    using System;

    public class Workspace : IWorkspace, IDisposable
    {
        private DbContext clsDataContext;
        
        public Workspace()
        {
            // Manage the current [thread-static] instance: cannot create a new instace if already exists one (not disposed yet)!
            if (SystemGlobal.CurrentWorkspace != null)
            {
                throw new InvalidOperationException("Cannot create a new workspace while there already exists a current one!");
            }
            else
            {
                SystemGlobal.SetCurrentWorkspace(this);
            }
        }

        public DbContextType GetDataContext<DbContextType>() where DbContextType : class
        {
            return clsDataContext as DbContextType;
        }

        public T CreateAttachedDbEntity<T>() where T : IDbEntity, new()
        {
            T newEntity = new T();
            clsDataContext.Set(newEntity.GetType()).Attach(newEntity);
            
            return newEntity;
        }

        public void SetDataContext<DbContextType>(DbContextType DataContext) where DbContextType : DbContext
        {
            throw new System.NotImplementedException();
        }

        public DbContext GetDataContext()
        {
            throw new System.NotImplementedException();
        }

        public T CreateDbEntity<T>() where T : IDbEntity, new()
        {
            throw new System.NotImplementedException();
        }

        public void Dispose()
        {
            // nothing to do here
        }
    }
}
